<html>

<head>
	<title>Welcome</title>
	
	<script type="text/javascript" src="ext/ext-base.js"></script> 
	<script type="text/javascript" src="ext/ext-all.js"></script> 

	<!--
	<script type="text/javascript" src="/ext-4.0.7/ext-all.js"></script> 
	-->

	<script type='text/javascript' src='js/jquery-1.6.4.min.js'></script>
	<link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css">
	<script type='text/javascript'>
		var j$ = jQuery.noConflict();
		
		function createWindow(title, width, height, closable) {
			var win = new Ext.Window({
				title: title,
				width: width,
				height: height,
				closable: !closable,
				layout: "fit",
				role: null,
				component_cache: {
					"reply": null,
					"message": null,
					"button": null
				},
				addMsg: function(data) {
					var cmp = this.component_cache["reply"]
					if (!cmp) {
						console.log(this.role + ": Fetching cache for reply");
						cmp = this.component_cache["reply"] =this.findByType("textarea")[1];
					}
					cmp.setValue(cmp.getValue() + data + "\n")
					cmp.getEl().dom.scrollTop = cmp.getEl().dom.scrollHeight;
				},
				addReply: function(data) {
					this.addMsg(data);
					
					if (this.role == "win") {
						var role = data.split(":")[0];
						if (data.search(role + ":file 0") == 0) {
							var win = window.roles[role];
							if (!win) {
								win = createWindow("Talking to " + role, 400, 300, false);
								win.role = role;
								win.show()
								window.roles[role] = win;
							}
							if (win) {
								data = data.substring(data.search(":") + 1)
								win.focusMessage();
								win.addReply(data);
								return;
							}
						}
					}
					//TODO
					if (data.search("file") == 0) {
						try {
							if (!this.filelist) {
								this.filelist = [];
							}
							
							alias = this.role
							data = data.split(" ").slice(1);
							status = parseInt(data[0])
							index = data[1]
							filesize = parseInt(data[2])
							filepath = data[3]
							this.addMsg("size " + filesize + ", status " + status + ", file " + filepath)
							
							if (status == 0){
								this.addMsg("data pushed");
								data = data.join(" ") + " " + alias
								this.filelist.push(data)
							} else if (status == 1) {
								wss.emit("file 2 " + index);
								this.addMsg("Client file path: " + filepath);
							} else if (status == 3) {
								console.log("Start sending")
								this.addMsg("Start sending")
								window.that = this
								//window.count = 10;
								window.size = filesize
								window.curr = 0
								window.file = filepath
								window.msgHandler = function(data) {
									if (data.search("data") == 0) {
										/*
										var msg = "data ";
										for (var j = 0; j < 1011; j++) {
											msg += String.fromCharCode("a".charCodeAt(0) + Math.ceil(Math.random() * 10))
										}
										debugger
										console.log(msg);
										wss.emit(msg);
										*/
										ajax({
											//url: "cgi-bin/GetFile.py",
											url: "file",
											type: "POST",
											dataType: "text",
											data:{file: window.file, seek: window.curr, size: 1011, type: "get" },
											success: function(response, xml) {
												that.addMsg(response)
												
												var end = false
												if (response) {
													response = response.split(" data ");
													var len = parseInt(response[0])
												
													window.curr += len;
													
													var res = response.slice(1).join(" data ");
													/*
													var textEncoder = new TextEncoder("utf8");
													var bytes = textEncoder.encode(res)
													res = ""
													for (var i = 0; i< bytes.length; i++) {
														res += String.fromCharCode(bytes[i])
													}*/
													
													wss.emit("data " + res)
												} else {
													end = true;
												}
												if (window.curr >= window.size) {
													end = true;
												}
												
												if (end) {
													console.log("End sending")
													window.that.addMsg("End sending")
													window.msgHandler = null;
												}
											},
											fail: function(status){
												that.addMsg("\nERROR:"+status + "\n")
											}
										});
										
									}
									if (data.search("disconnected") == 0) {
										addalias = data.split(" ")[1]
										if (window.alias == addalias) {
											that.addMsg("End sending")
											window.msgHandler = null;
										}
									}
									/*
									if (window.count-- <= 0) {
										that.addMsg("End sending")
										window.msgHandler = null;
									}
									*/
								}
								window.msgHandler("data");
							} else if (status == 2) {
								wss.emit("file 3 " + index);
								this.addMsg("Client file path: " + filepath);
								
								try {
									console.log("starting receiving")
									this.addMsg("starting receiving")
									window.that = this;
									window.size = filesize
									window.recv_size = 0
									window.file = filepath
									window.alias = alias
									window.msgHandler = function(data) {
										if (data) {
											if (data.search("data") == 0) {
												var size = 0;
												if (window.size - window.recv_size > 1024) {
													size = recv_size + 1024 - 5
												} else {
													size = window.size
												}
												that.addMsg(data);
												that.addMsg(data.length + ", " + size + ", " + window.size)
												
												window.recv_size = size
												data = data.split(" ").slice(1).join(" ")
												
												ajax({
													//url: "cgi-bin/FileSize.py",
													url: "file",
													type: "POST",
													dataType: "text",
													data:{file: window.file, type: "post", data: data},
													success: function(response, xml) {
														that.addReply(response)
												
														wss.emit("data ");
													},
													fail: function(status){
														that.addReply("\nERROR on write:"+status + "\n")
													}
												});
											}
										}
										var end = false
										if (window.recv_size == window.size) {
											end = true;
										}
										if (end == false && data.search("disconnected") == 0) {
											addalias = data.split(" ")[1]
											if (window.alias == addalias) {
												end = true;
											}
										}
										if (end) {
											console.log("end receiving")
											that.addMsg("end receiving")
											window.msgHandler = null;
											
											ajax({
												//url: "cgi-bin/FileSize.py",
												url: "file",
												type: "POST",
												dataType: "text",
												data:{file: window.file, type: "close", inout: "post"},
												success: function(response, xml) {
													that.addReply(response)
												},
												fail: function(status){
													that.addReply("\nERROR on close:"+status + "\n")
												}
											});
										}
									}
								} catch(e){
									console.log(e)
								}
							}
						}catch(e) {
							console.log(e)
						}
					}
				},
				clsReply: function() {
					var cmp = this.component_cache["reply"]
					if (!cmp) {
						console.log(this.role + ": Fetching cache for reply");
						cmp = this.component_cache["reply"] =this.findByType("textarea")[1];
					}
					cmp.setValue("");
				},
				hookButton: function() {
					var cmp = this.component_cache["button"];
					if (!cmp) {
						console.log(this.role + ": Fetching cache for button");
						cmp = this.component_cache["button"] = this.findByType("button")[0];
					}
					cmp.handler(cmp)
				},
				getMessage: function() {
					var cmp = this.component_cache["message"];
					if (!cmp) {
						console.log(this.role + ": Fetching cache for message");
						cmp =  this.component_cache["message"] = this.findByType("textarea")[0];
					}
					return cmp.getValue()
				},
				clsMessage: function() {
					var cmp = this.component_cache["message"]
					if (!cmp) {
						console.log(this.role + ": Fetching cache for message");
						cmp =  this.component_cache["message"] =  this.findByType("textarea")[0];
					}
					cmp.setValue("")
				},
				focusMessage: function() {
					this.show();
					var cmp = this.component_cache["message"]
					if (!cmp) {
						console.log(this.role + ": Fetching cache for message");
						cmp =  this.component_cache["message"] =  this.findByType("textarea")[0];
					}
					cmp.focus(false, 100)
				},
				appendReturn: function() {
					cmp = this.component_cache["message"];
					if (!cmp) {
						console.log(this.role + ": Fetching cache for message");
						cmp =  this.component_cache["message"] =  this.findByType("textarea")[0];
					}
					cmp.setValue(cmp.getValue() + "\n")
				},
				listeners: {
					"close": function() {
						console.log(this.role + ": closed")
						delete window.roles[this.role];
					}
				},
				closeWindow: function() {
					if (this.role == "win") {
						this.addReply("console cannot be closed!\n");
					} else {
						this.focusNextWindow();
						this.close();
					}
				},
				focusNextWindow: function() {
					var found = false;
					var changed = false;
					for (key in window.roles) {
						if (key == this.role) {
							found = true;
						}
						else if (found) {
							window.roles[key].focusMessage();
							changed = true;
							break;
						}
					}
					if (!changed) {
						window.win.focusMessage();
					}
				},
				sendMessage: function(data) {
					if (data) {
						//client command
						if (data[0] == "@") {
							data = data.substr(1)
							if (data == "close") {
								this.closeWindow();
							} else if (data == "cls") {
								this.clsReply();
							}else if (data == "order") {
								var x = 0, y = 0;
								for (key in window.roles) {
									var win = window.roles[key];
									win.setPosition(x, y);
									x += 50;  y += 50;
								}
							} else if (data == "roles") {
								result = "";
								for (key in window.roles) {
									result += key + "\n";
								}
								this.addReply(result);
							}else {
								var win = window.roles[data];
								if (!win) {
									win = createWindow("Talking to " + data, 400, 300, false);
									win.role = data;
									win.show()
									window.roles[data] = win;
								}
								win.focusMessage();
							}
						}
						else if (data[0] == "#") {
							if(this.role == "win") {
								this.addReply("should assign a role!\n");
							} else {
								data = data.substr(1)
								if (data == "file") {
									info = this.filelist.pop()
									if (info) {
										param = info.split(" ");
										if (param.length > 4) {
											status = parseInt(param[0])
											index = param[1]
											filesize = parseInt(param[2])
											filepath = param[3]
											alias = param[4]
											
											wss.emit("file 1 " + index + " " + alias)
										}
									}
								} else {
									that = this;
									ajax({
										//url: "cgi-bin/FileSize.py",
										url: "file",
										type: "POST",
										dataType: "text",
										data:{file: data, type: "size"},
										success: function(response, xml) {
											that.addReply(response)
											wss.emit("file 0 " + parseInt(response) + " " + data + " " + that.role)
											
											window.msgHandler = null;
										},
										fail: function(status){
											that.addReply("\nERROR:"+status + "\n")
										}
									});
								}
							}
						}
						else {
							if (this.role == "win") {
								wss.emit(data);
							}
							else {
								wss.emit("send " + this.role + " " + data);
							}
							this.addReply("me:" + data + "\n")
						}
					}
				},
				items: [{
					xtype: "panel",
					layout: "border",
					border: false,
					items:[{
						xtype: "panel",
						region: "south",
						height: 50,
						split: true,
						layout: "fit",
						border: false,
						items: [{
							xtype: "panel",
							layout: "border",
							border: false,
							items: [{
								xtype: "panel",
								region: "center",
								border: false,
								items: [{
									xtype: "textarea",
									width: "100%",
									height: "100%",
									onkeydown: function() {
										alert("Key down");
									},
									listeners: {
										"render": function(p) {
											p.getEl().on("keydown", function(event, e) {
												if (event.keyCode == 13) {
													var cmp = Ext.getCmp(e.id);
													cmp = cmp.findParentByType("window");
													if (event.ctrlKey) {
														event.ctrlKey = false;
														//giving return to textarea
														cmp.appendReturn();
													} else {
														cmp.hookButton();
														//stop giving return to textarea
														event.preventDefault();
													}
												}
												if (event.keyCode == 9) {
													var cmp = Ext.getCmp(e.id);
													cmp = cmp.findParentByType("window");
													cmp.focusNextWindow();
													//stop bubbling
													event.preventDefault();
												}
												if (event.keyCode == 81 && event.ctrlKey) {
													var cmp = Ext.getCmp(e.id);
													cmp = cmp.findParentByType("window");
													cmp.closeWindow();
													//stop bubbling
													event.preventDefault();
												}
											})
										}
									}
								}]
							},{
								xtype: "panel",
								region: "east",
								border: false,
								width: 50,
								items: [{
									xtype: "button",
									text: "send",
									width: "100%",
									height: "100%",
									handler: function(e) {
										var cmp = Ext.getCmp(e.id);
										cmp = cmp.findParentByType("window");
										var data = cmp.getMessage();
										cmp.clsMessage();
										cmp.sendMessage(data);
									}
								}]
							}]
						}]
					},{
						xtype: "panel",
						region: "center",
						border: false,
						items: [{
							xtype: "textarea",
							height: "100%",
							width: "100%",
							readOnly: true
						}]
					}]
				}]
			});
			return win;
		}
		Ext.onReady(function(){
			window.win = createWindow("Console", 400, 300, true);
			window.win.role = "win";
			window.win.show()
			window.win.focusMessage();
			window.roles = {"win": window.win}
		});
	</script>

	<script type="text/javascript" src="ajax.js"></script>
	<script type="text/javascript" src="websocket.js"></script>
	<script type="text/javascript">
		var wss = new WSS("ws://stophin:8000/ws")
		setTimeout(function() {
			wss.emit("alias Ann")
		}, 3000);
		function clickOK() {
			ajax({
				url:"/cgi-bin/CGI.py",
				//url: "/cgi-bin/Lunch.py",
				type: "POST",
				data:{user: window.document.all.user.value},
				dataType: "text",
				success: function(response, xml) {
					window.document.all.response.innerHTML = response;
				},
				fail: function(status){
					window.document.all.response.innerHTML = "ERROR" + status;
				}
			});
		}
	</script>
</head>
<body>
	<div>
		<form id="mainForm" method="POST" action="/cgi-bin/CGI.py">
			<input type="text" id="user" name="user"></input>
			<button type="button" onclick="clickOK()">OK</button>
		</form>
		<div id="response"></div>
	</div>
</body>
</html>